/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.sapra.dao;

import caintra.Sapra.Internacional.DBManager;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import org.sapra.logon.dLogin;



public class Autenticacion
{

    public static void Send(String msj,String to,String subject,String accion,int id,String empresa)
    {

        String host ="smtp.gmail.com";//Suponiendo que el servidor SMTPsea la propia máquina
        String from ="sapra.caintra@gmail.com";


        System.out.println ("Prueba para enviar un mail..." + new java.util.Date());

        Properties prop = new Properties();

        prop.put("mail.smtp.host", host);
        prop.put("mail.smtp.starttls.enable","true");
        prop.put("mail.smtp.port", 587);
        /*Esta línea es la que indica al API que debe autenticarse*/
        prop.put("mail.smtp.auth", "true");

        /*Añadir esta linea si queremos ver una salida detallada del programa*/
        //prop.put("mail.debug", "true");
        boolean envio=true;
        int usuario=0;
        try{

            SMTPAuthentication auth = new SMTPAuthentication();
            Session session = Session.getInstance(prop , auth );
            Message msg = getMessage(session, from, to,msj,subject);
            System.out.println ("Enviando ..." );

            try {
                Transport.send(msg);
            System.out.println ("Mensaje enviado!");
                envio=true;
            } catch (Exception e) {
                System.out.println ("Mensaje NO enviado!");
                envio=false;
            }finally{
                usuario=dLogin.getUser().getUsuarioId();
                int res=0;
                if(envio)
                    res=1;


                String sql="";
                sql="INSERT INTO log_correo(nombre,empresa,id,fecha,usuario,status)"
                    + " VALUES("+"'"+accion.toUpperCase()+"','"+empresa+"',"+id+",NOW(),"+usuario+","+res+");";

                try {
                    DBManager.insert(sql);
                    System.out.println ("Jalo Insert");
                } catch (Exception e) {
                    System.out.println ("No jalo insert");
        }
            }
        }

        catch (Exception e)
        {

            ExceptionManager.ManageException(e);

        }finally{

        }

    }

    private static MimeMessage getMessage(Session session, String from, String to,String msj,String subject)
    {

        try{

            MimeMessage msg = new MimeMessage(session);
            msg.setText(msj);
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            msg.setFrom(new InternetAddress(from,"SAPRA"));
            msg.setSubject(subject);
            msg.setContent(msj, "text/html");
            return msg;

        }

        catch (java.io.UnsupportedEncodingException ex)
        {

            ExceptionManager.ManageException(ex);
            return null;

        }

        catch (MessagingException ex)
        {

            ExceptionManager.ManageException(ex);
            return null;

        }

    }



}

class SMTPAuthentication extends javax.mail.Authenticator
{

    @Override
    public PasswordAuthentication getPasswordAuthentication()
    {

        String username = "sapra.caintra@gmail.com";

        String password = "caintra2011";

        return new PasswordAuthentication(username, password);

    }

}

class ExceptionManager
{

    public static void ManageException (Exception e)
    {

        System.out.println ("Se ha producido una exception");

        System.out.println (e.getMessage());

        e.printStackTrace(System.out);

    }

}